package hn.cch.spring.boot.service.impl;

import hn.cch.common.service.RedisService;
import hn.cch.spring.boot.constant.HttpConstant;
import hn.cch.spring.boot.service.SessionService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.Enumeration;
import java.util.Objects;
import java.util.UUID;

@Service
public class SessionServiceImpl implements SessionService {

    private final static Logger logger = LoggerFactory.getLogger(SessionServiceImpl.class);

    @Autowired
    private RedisService redisService;

    public void listAttributes(HttpSession httpSession) {
        Enumeration<String> attributeNames = httpSession.getAttributeNames();
        while (attributeNames.hasMoreElements()) {
            String element = attributeNames.nextElement();
            logger.info("element:{}", element);
            Object attribute = httpSession.getAttribute(element);
            logger.info("attribute:{}", attribute);
        }
    }

    public HttpServletRequest compareSession(HttpServletRequest httpServletRequest) {
        HttpSession httpSession = httpServletRequest.getSession();
        // JSESSIONID
        String id = httpSession.getId();
        httpServletRequest.changeSessionId();
        logger.info("id:{}", id);

        listAttributes(httpSession);

        Object object = httpSession.getAttribute(HttpConstant.TOKEN);
        if (object == null) {// 首次访问session为空需要登陆
            // 模拟登陆过程添加session
            httpSession.setAttribute(HttpConstant.TOKEN, UUID.randomUUID().toString());
        } else if (object instanceof String) {// 再次对比session是否一致
            String string = (String) object;
            logger.info("string:{}", string);
            String session = redisService.get(String.format(HttpConstant.SESSION, id));
            logger.info("session:{}", session);
            if (Objects.equals(string, session)) {
                // session匹配后就更新一次防止重复
                httpSession.setAttribute(HttpConstant.TOKEN, HttpConstant.SESSION);
            }
        }

        return httpServletRequest;
    }

}
